package cn.js189.uqc.util;

import cn.js189.common.constants.HttpConstant;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.UUID;


public class HttpClientHelperForEop {
	
	private static final  Logger logger = LoggerFactory.getLogger(HttpClientHelperForEop.class);
	private HttpClientHelperForEop(){
	    super();
	}
	
    /**
     * 
     * 描述: http_get方法(此处的app-key和value只限于一致性二期使用，后面的都是使用查询域的appkey和value)
     * @param url
     * @return
     * @author     fang_cha
     * date        2014-05-23
     * --------------------------------------------------
     * 修改人            修改日期       修改描述
     * fang_cha        2014-05-23       创建
     * --------------------------------------------------
     * @Version  Ver1.0
     */
    public static String get(String url) {
        logger.info("请求url："+url);
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpGet httpget=new HttpGet(url);
        httpget.addHeader("Content-Type", "application/json;charset=utf-8");
        httpget.addHeader("X-APP-ID", "fdd0ddf5bbdd405cb51de10bc1aa3e75");
        httpget.addHeader("X-APP-KEY", "0da3619d436c3111c72a9195b28552da");
        httpget.addHeader("X-CTG-Request-ID", "92598bee-7d30-4086-qqqq-a7be6bd2cda0");
        httpget.addHeader("X-CTG-Porvince-ID", "832000");
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).build();
        httpget.setConfig(requestConfig);
        
        
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            HttpResponse response=httpclient.execute(httpget);
            //发送GET,并返回一个HttpResponse对象，相对于POST，省去了添加NameValuePair数组作参数
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity());
                //得到返回的字符串
            }
        } catch (Exception e) {
            logger.debug("请求报错:{}",e.getMessage());
            if(e.getMessage().equals("Read timed out")){
            	result = "10002";
            }
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }

    public static String getWithDcoss(String url,Map<String,String> headMap){
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpGet httpGet=new HttpGet(url);
        httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
        httpGet.addHeader("X-APP-ID", EInvoiceUtil.APP_KEY);
        httpGet.addHeader("X-APP-KEY", EInvoiceUtil.APP_SECRET);
        httpGet.addHeader("X-CTG-Request-ID", UUID.randomUUID().toString());
        for(Map.Entry<String, String> entry:headMap.entrySet()){
            httpGet.addHeader(entry.getKey(), entry.getValue());
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpGet.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            HttpResponse response=httpclient.execute(httpGet);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity());
                logger.debug("请求回参{}",result);
            }
        } catch (Exception e) {
            logger.debug("请求报错:{}",e.getMessage());
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }

    /**
     * 计费新接口升级
     */
    public static String postToBill(String url, String requestJson, String areaCode) {
        logger.debug("actionUrl:{} ", url);
        String result = "";
        long callStart = System.currentTimeMillis();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

        if(url.contains("132.252.129.160")){
            httpPost.addHeader("X-APP-ID", EInvoiceUtil.TEST_APP_KEY);
            httpPost.addHeader("X-APP-KEY", EInvoiceUtil.TEST_APP_SECRET);
        }else{
            httpPost.addHeader("X-APP-ID", EInvoiceUtil.APP_KEY);
            httpPost.addHeader("X-APP-KEY", EInvoiceUtil.APP_SECRET);
        }
        if (!StringUtils.isBlank(areaCode)) {
            String xRegionId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
            httpPost.addHeader("X-CTG-Region-ID", xRegionId);
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost.setConfig(requestConfig);
        try (CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(requestJson,HttpConstant.UTF_ENCODING);
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            //如果状态码为200,就是正常返回 ,对端返回400错误也按正常返回处理
            if (response.getStatusLine().getStatusCode() == 200 ||response.getStatusLine().getStatusCode() == 400) {
                result = EntityUtils.toString(response.getEntity(), HttpConstant.UTF_ENCODING);
            }
        } catch (Exception e) {
            logger.error("请求异常:{}", e.getMessage());
        } finally {
            long callEnd = System.currentTimeMillis();
            logger.info("actionUrl:{} process time:{}", url, (callEnd - callStart));
        }
        return result;
    }
    
    public static String newPostToBill(String url, String requestJson, String areaCode) {
        logger.debug("actionUrl:{} ", url);
        String result = "";
        long callStart = System.currentTimeMillis();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

        httpPost.addHeader("X-APP-ID", EInvoiceUtil.EOP_APP_KEY);
        httpPost.addHeader("X-APP-KEY", EInvoiceUtil.EOP_APP_SECRET);

        if (!StringUtils.isBlank(areaCode)) {
            String xRegionId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
            httpPost.addHeader("X-CTG-Region-ID", xRegionId);
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost.setConfig(requestConfig);
        try (CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(requestJson,HttpConstant.UTF_ENCODING);
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            //如果状态码为200,就是正常返回 ,对端返回400错误也按正常返回处理
            if (response.getStatusLine().getStatusCode() == 200 ||response.getStatusLine().getStatusCode() == 400) {
                result = EntityUtils.toString(response.getEntity(),HttpConstant.UTF_ENCODING);
            }
        } catch (Exception e) {
            logger.error("请求异常:{}", e.getMessage());
        } finally {
            long callEnd = System.currentTimeMillis();
            logger.info("actionUrl:{} process time:{}", url, (callEnd - callStart));
        }
        return result;
    }

    /**
     * 携号转网post接口
     * Description: <br> 
     *  
     * @author yangyang<br>
     * 2019年6月11日
     * @param url
     * @return String<br>
     */
    public static String postWithMNP(String url,String jsonString,int ...reqTimeout) {
        logger.debug("请求入参{}",jsonString);
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpPost httpPost=new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        if(url.contains("132.252.129.160")){
            httpPost.addHeader("X-APP-ID", EInvoiceUtil.TEST_APP_KEY);
            httpPost.addHeader("X-APP-KEY", EInvoiceUtil.TEST_APP_SECRET);
        }else{
            httpPost.addHeader("X-APP-ID", EInvoiceUtil.APP_KEY);
            httpPost.addHeader("X-APP-KEY", EInvoiceUtil.APP_SECRET);
        }
        int timeout = 10000;
        if(reqTimeout !=null&&reqTimeout.length>0){
            timeout = reqTimeout[0];
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        httpPost.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(jsonString,HttpConstant.UTF_ENCODING);
            httpPost.setEntity(entity);
            HttpResponse response=httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity(),HttpConstant.UTF_ENCODING);
                logger.info("请求回参{}",result);
            }
        } catch (Exception e) {
            logger.info("请求报错:{}",e.getMessage());
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.info("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }

    public static String postWithMNPWithHeader(String url,String jsonString,Map<String,String> headMap) {
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpPost httpPost=new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.addHeader("X-APP-ID", EInvoiceUtil.APP_KEY);
        httpPost.addHeader("X-APP-KEY", EInvoiceUtil.APP_SECRET);
        for(Map.Entry<String, String> entry:headMap.entrySet()){
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(jsonString, HttpConstant.UTF_ENCODING);
            httpPost.setEntity(entity);
            HttpResponse response=httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity());
                logger.debug("请求回参{}",result);
            }
        } catch (Exception e) {
            logger.debug("请求报错:{}",e.getMessage());
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }
    
    public static String patchWithMNPWithHeader(String url,String jsonString,Map<String,String> headMap) {
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpPatch httpPatch=new HttpPatch(url);
        httpPatch.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPatch.addHeader("X-APP-ID", EInvoiceUtil.APP_KEY);
        httpPatch.addHeader("X-APP-KEY", EInvoiceUtil.APP_SECRET);
        for(Map.Entry<String, String> entry:headMap.entrySet()){
        	httpPatch.addHeader(entry.getKey(), entry.getValue());
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpPatch.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(jsonString, HttpConstant.UTF_ENCODING);
            httpPatch.setEntity(entity);
            HttpResponse response=httpclient.execute(httpPatch);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity());
                logger.debug("请求回参{}",result);
            }
        } catch (Exception e) {
            logger.debug("请求报错:{}",e.getMessage());
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }
    
    public static String getWithEopAppKey(String url){
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpGet httpGet=new HttpGet(url);
        httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
        httpGet.setHeader("X-APP-ID",EInvoiceUtil.EOP_APP_KEY);
        httpGet.setHeader("X-APP-KEY",EInvoiceUtil.EOP_APP_SECRET);
        httpGet.addHeader("X-CTG-Request-ID", UUID.randomUUID().toString());
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httpGet.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            HttpResponse response=httpclient.execute(httpGet);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity());
                logger.debug("请求回参{}",result);
            }
        } catch (Exception e) {
            logger.debug("请求报错:{}",e.getMessage());
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }

    public static String postToEOPWithTime(String url,String jsonString,int time) {
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpPost httpPost=new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.addHeader("X-APP-ID", EInvoiceUtil.EOP_APP_KEY);
        httpPost.addHeader("X-APP-KEY", EInvoiceUtil.EOP_APP_SECRET);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
        httpPost.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(jsonString, HttpConstant.UTF_ENCODING);
            httpPost.setEntity(entity);
            HttpResponse response=httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity(),HttpConstant.UTF_ENCODING);
                logger.info("请求回参{}",result);
            }
        } catch (Exception e) {
            logger.info("请求报错:{}",e.getMessage());
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.info("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }
    
    public static String postWithHeader(String url,String jsonString,Map<String,String> headMap,int reqTimeout) {
        String result ="";
        long callStart=System.currentTimeMillis();
        HttpPost httpPost=new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

        for(Map.Entry<String, String> entry:headMap.entrySet()){
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }
        int timeout = 10000;
        if(StringUtils.isNotBlank(Integer.toString(reqTimeout))&& reqTimeout>0){
            timeout = reqTimeout;
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        httpPost.setConfig(requestConfig);
        try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
            StringEntity entity = new StringEntity(jsonString, HttpConstant.UTF_ENCODING);
            httpPost.setEntity(entity);
            HttpResponse response=httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
                result=EntityUtils.toString(response.getEntity(),HttpConstant.UTF_ENCODING);
                logger.debug("请求回参{}",result);
            }
        } catch (Exception e) {
            logger.debug("请求报错:{}",e.getMessage());
        }finally {
            long callEnd = System.currentTimeMillis();
            logger.debug("actionUrl:{} process time:{}",url,(callEnd - callStart));
        }
        return result;
    }
}
